﻿@{
    Layout = null;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>监控界面</title>
    <script src="~/js/signalr/dist/browser/signalr.js">
        const { signalR } = require("../../wwwroot/js/signalr/dist/browser/signalr");
    </script>
    <link rel="stylesheet" type="text/css" href="~/css/floor1/floor11.css">
    <link rel="stylesheet" type="text/css" href="~/css/floor1/index.css">
    <link rel="stylesheet" type="text/css" href="~/css/bootstrap.min.css">
    <script type="text/javascript" src="~/lib/jquery/1.9.1/jquery.min.js"></script>

    <script type="text/javascript" src="~/js/bootstrap.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }


        html {
            width: 100%;
            height: 100%;
        }

        body {
            width: 100%;
            height: 100%;
            overflow: hidden;
        }


        #mountNode {
            width: 100%;
            height: 100%;
        }

        #header {
            font-family: '楷体';
            padding-top: 10px;
            text-align: center;
        }

        .plc {
            margin: 20px;
            
        }

        .wcs {
            margin: 20px;
            
        }

        .Tooltip{
            background:#fff;
            border:1px solid #ccc;
            padding:20px;
            border-radius:20px;
        }

        .btn button {
            font-family: '楷体';
            font-weight: bolder;
            width: 100px;
            height: 40px;
            border: 0px;
            border-radius: 20px;
            margin: 2px;
        }

            .btn button:hover {
                background: rgb(30, 8, 222);
                cursor: pointer;
            }
.ibox{
    display:flex;
  
   
    justify-items:center;
}
        .btn {
            padding: 0 50px;
            display: flex;
            flex-direction: row;
            align-items: center;
        }

        .show {
            display:inline;
            font-weight:bolder;
            color:  rgb(30, 8, 222);
        }

        .active {
            background: rgb(30, 8, 222);
        }

        .info > ul > li {
            font-size: 14px;
            margin: 1px;
            list-style: none;
            display:flex;
            font-family:'黑体'  }
    </style>

</head>

<body>
    <input id="signalRUrl" value="@ViewBag.signalRUrl" type="hidden">

    <div id="header">
        <h1>设备实时监控系统（ <span id="LHeader"></span>楼设备）</h1>
        <div class="btn">
            <button onclick="changeLayer('1')" class="active">线体一层</button>
            <button onclick="changeLayer('2')">线体二层</button>
            <button onclick="changeLayer('3')">线体三层</button>
            <button onclick="changeLayer('4')">线体四层</button>

        </div>
        <div class="tt">
        </div>
    </div>
    <div id="mountNode"></div>


    <script src="~/js/g6.min.js"></script>
    <script>
        var plcData = {}, wcsData = {};
        
        //处理跳转页面到时候链接signalR 地址改变
        var url;
        url = window.location.href;
        //console.log("url = " + url);
            
        // 获取到配置中的 signalRURL
        var signalRUrl = $("#signalRUrl").val();
        if (url.indexOf("172.21.224.254") != -1) {
            signalRUrl = signalRUrl.replace("192.168.60.245:8006", "172.21.224.254:8006");
            signalRUrl = signalRUrl.replace("192.168.60.240:8006", "172.21.224.254:10240");
            signalRUrl = signalRUrl.replace("192.168.60.241:8006", "172.21.224.254:10241");
        }
        //创建signalR连接
        var connection = new signalR.HubConnectionBuilder().withUrl(signalRUrl).withAutomaticReconnect([10000, 4000, 10000, 10000]).build();
        connection.serverTimeoutInMilliseconds = 30000;
        const data = {
            currentLayer: 1,
            currentFloor: getQueryVariable('floor'),
        }

        //提示框
        const tooltip = new G6.Tooltip({
            offsetX: 80,
            offsetY: -80,
             className: 'Tooltip',
            getContent(e) {
                const outDiv = document.createElement('div');

                if (e.item.getModel().class == 'line') {

                    outDiv.innerHTML = `
                     <div class="plc info" style="float:left">
                     <h4>plc</h4>
                     <ul >
                       <li>设备编号:<span class="show">${e.item.getModel().station}</span></li>
                       <li>任务号:  <span class="show">${e.item.getModel().data.TaskCode}</span></li>
                       <li>托盘条码:<span class="show">${e.item.getModel().data.PalletBarcode}</span></li>
                       <li>握手类型:<span class="show">${e.item.getModel().data.ActionType}</span></li>
                       <li>托盘类型:<span class="show">${e.item.getModel().data.PalletType}</span></li>
                       <li>故障代码:<span class="show">${e.item.getModel().data.AlrmCode}</span></li>
                     </ul>
                     </div>
                     <div class="wcs info" style="float:right">
                       <h4>wcs</h4>
                     <ul>
                       <li>设备编号: ${e.item.getModel().station}</li>
                     </ul>
                     </div>
  `
                }
                else if(e.item.getModel().class == 'sc'){
                      outDiv.innerHTML = `<h4 style="text-align:center"> 堆垛机编号:${e.item.getModel().station}</h4>
                      <div class="ibox">
                      <div class=" info" >
                     
                     <ul >
  
                       <li>堆垛机手自动:  <span class="show">${e.item.getModel().data.StackerHandAutomatic== 1?"自动":"手动" }</span></li>
                       <li>堆垛机闲忙:    <span class="show">${e.item.getModel().data.StackerBusy== 1?"空闲":"忙"}</span></li>
                       <li>货叉有盘:      <span class="show">${e.item.getModel().data.Forkhasaterial?"是":"否"}</span></li>
                       <li>堆垛机报警:    <span class="show">${e.item.getModel().data.StackerAlarm?"是":"否"}</span></li>
                       <li>堆垛机运行信号:<span class="show">${e.item.getModel().data.Stackerrunningsignal?"否":"是"}</span></li>
                       <li>堆垛机任务完成:<span class="show">${e.item.getModel().data.StackerTaskCompletion?"是":"否"}</span></li>
                       <li>堆垛机任务完成:<span class="show">${e.item.getModel().data.StackerTaskCompletion?"是":"否"}</span></li>
                       <li>安全门在线信号:<span class="show">${e.item.getModel().data.SecurityDooronLine?"在线":"离线"}</span></li>
                       <li>上位机更新状态:<span class="show">${e.item.getModel().data.yuliu1?"是":"否"}</span></li>
                       <li>请求WSC红外拍照:<span class="show">${e.item.getModel().data.yuliu2?"是":"否"}</span></li>
                       <li>取料完成:<span class="show">${e.item.getModel().data.yuliu4?"是":"否"}</span></li>
                       <li>堆垛机报警代码:  <span class="show">${e.item.getModel().data.Stackeralarmcode}</span></li>
                        <li>当前工作序号:  <span class="show">${e.item.getModel().data.Currentjobnumber}</span></li>
                       <li>当前工作命令代码: <span class="show">${e.item.getModel().data.Currentworkordercode || "当前无工作命令"}</span></li>
                     </ul>
                     </div>
                     <div class="info" >
                     
                     <ul>
                      
                       <li>当前行:  <span class="show">${e.item.getModel().data.Currentline}</span></li>
                       <li>当前列:  <span class="show">${e.item.getModel().data.Currentcolumn}</span></li>
                       <li>当前层:  <span class="show">${e.item.getModel().data.Currentlayer}</span></li>
                      
                       <li>启始行: <span class="show"> ${e.item.getModel().data.StartlinetoPC}</span></li>
                       <li>启始列: <span class="show"> ${e.item.getModel().data.StartcolumntoPC}</span></li>
                       <li>启始列: <span class="show"> ${e.item.getModel().data.StartcolumntoPC}</span></li>
                       <li>启始层: <span class="show"> ${e.item.getModel().data.StartlayertoPC}</span></li>
                       <li>目标行: <span class="show"> ${e.item.getModel().data.TargetlinetoPC}</span></li>
                       <li>目标行: <span class="show"> ${e.item.getModel().data.TargetlinetoPC}</span></li>
                       <li>目标列: <span class="show"> ${e.item.getModel().data.TargetcolumntoPC}</span></li>
                       <li>目标层: <span class="show"> ${e.item.getModel().data.TargetlayertoPC}</span></li>
                     </ul>
                     </div>
                       </div>
  `
                }  else if(e.item.getModel().class == 'eleLayer'){
                          outDiv.innerHTML = `
                      <div class="ibox">
                      <div class=" info" >
                     <h4 > PLC数据</h4>
                     <ul >
                      
                       <li>提升机编号:  <span class="show">${e.item.getModel().station}</span></li>
                       <li>自动:  <span class="show">${e.item.getModel().data.Auto==1?"自动":"手动"}</span></li>
                       <li>繁忙:    <span class="show">${e.item.getModel().data.Busy==1?"繁忙":"空闲"}</span></li>
                       <li>上层有盘:      <span class="show">${e.item.getModel().data.UpMaterial==1?"有盘":"无盘"}</span></li>
                       <li>下层有盘:    <span class="show">${e.item.getModel().data.DownMaterial==1?"有盘":"无盘" }</span></li>
                       <li>任务完成:<span class="show">${e.item.getModel().data.TaskComplete==1?"完成":"无" }</span></li>
                       <li>报警:<span class="show">${e.item.getModel().data.LiftAlrm==1?"报警":"无" }</span></li>
                       <li>报警代码:<span class="show">${e.item.getModel().data.LiftAlrmCode}</span></li>
                       <li>模拟自动:<span class="show">${e.item.getModel().data.Analogautomatic==1?"模拟中":"无"}</span></li>
                       <li>当前楼:<span class="show">${e.item.getModel().data.CurrentFloor}</span></li>
                       <li>当前层:<span class="show">${e.item.getModel().data.CurrentLayer}</span></li>
                       <li>当前上层功能:<span class="show">${e.item.getModel().data.CurrentUpFunction}</span></li>
                       <li>当前下层功能:  <span class="show">${e.item.getModel().data.CurrentDownFunction}</span></li>
                       
                     </ul>
                     </div>
                     <div class="info" >
                     <h4>上层仓位</h4>
                     <ul>
                      
                       <li>上层设备编号:  <span class="show">${e.item.getModel().data.UpEquipmentCode}</span></li>
                       <li>上层目标设备号:  <span class="show">${e.item.getModel().data.UpTaskCode}</span></li>
                       <li>上层托盘条码: <span class="show"> ${e.item.getModel().data.UpPalletBarcode}</span></li>
                       <li>上层握手类型: <span class="show"> ${e.item.getModel().data.UpActionType}</span></li>
                       <li>上层托盘类型: <span class="show"> ${e.item.getModel().data.UpPalletType}</span></li>
                       <li>上层故障代码: <span class="show"> ${e.item.getModel().data.UpAlrmCode}</span></li>
                       <li>上层预留: <span class="show"> ${e.item.getModel().data.UpReserve}</span></li>
                       <li>上层预留: <span class="show"> ${e.item.getModel().data.UpReserve2}</span></li>
                       <li>上层预留: <span class="show"> ${e.item.getModel().data.UpReserve3}</span></li>
                       <li>上层预留: <span class="show"> ${e.item.getModel().data.UpReserve4}</span></li>
                     </ul>
                     </div>
                     <div class="info" >
                     <h4>下层仓位</h4>
                     <ul>
                      
                       <li>下层设备编号:  <span class="show">${e.item.getModel().data.DownEquipmentCode}</span></li>
                       <li>上层目标设备号:  <span class="show">${e.item.getModel().data.DownTaskCode}</span></li>
                       <li>下层托盘条码: <span class="show"> ${e.item.getModel().data.DownPalletBarcode}</span></li>
                       <li>下层握手类型: <span class="show"> ${e.item.getModel().data.DownActionType}</span></li>
                       <li>下层托盘类型: <span class="show"> ${e.item.getModel().data.DownPalletType}</span></li>
                       <li>下层故障代码: <span class="show"> ${e.item.getModel().data.DownAlrmCode}</span></li>
                       <li>下层预留: <span class="show"> ${e.item.getModel().data.DownReserve}</span></li>
                       <li>下层预留: <span class="show"> ${e.item.getModel().data.DownReserve2}</span></li>
                       <li>下层预留: <span class="show"> ${e.item.getModel().data.DownReserve3}</span></li>
                       <li>下层预留: <span class="show"> ${e.item.getModel().data.DownReserve4}</span></li>
                     </ul>
                    </div>
               </div>`
                }
                else 
                {
                    outDiv.innerHTML = `
                        <div class="plc">

                                <ul>
                                  <li>设备编号: ${e.item.getModel().station}</li>
                                </ul>
                        </div>

                                                                                                                                                                                                      `
                }


                return outDiv
            },
            itemTypes: ['node']
        });

        // 创建 G6 图实例
        const graph = new G6.Graph({
            container: 'mountNode', // 指定图画布的容器 id，与第 9 行的容器对应
            fitCenter: true,
            // enabledStack: true,
            // 画布宽高
            width: document.getElementById('mountNode').offsetWidth,
            height: document.getElementById('mountNode').offsetHeight,
            modes: {
                default: ['drag-canvas', 'zoom-canvas'],
            },
            plugins: [tooltip],
            animate: true,

        });


        $.ajax({
            type: "POST",
            url: "/MonitorEditor/GetMonitorConfigInfoByFloor",
            data: {
                floor: getQueryVariable('floor') + '1'
            },
            dataType: "JSON",
            success: function(result) {

                let Data = JSON.parse(result[0].json);

                graph.data(Data)
                graph.render();


                console.log("读取" + getQueryVariable('floor') + '1')
                console.log(Data)

            }
        });
        var f = '';
        window.onload = function() {







            if (getQueryVariable('floor') == 'a') {
                f = 1
            } else if (getQueryVariable('floor') == 'b') {
                f = 2
            } else if (getQueryVariable('floor') == 'c') {
                f = 3
            } else if (getQueryVariable('floor') == 'd') {
                f = 4
            } else if (getQueryVariable('floor') == 'e') {
                f = 5
            }
            document.getElementById('LHeader').innerHTML = f;

            console.log(data.currentFloor + "楼层，第" + data.currentLayer + "层线体" + "    Floor" + f + "CallByHub")
            // 监听服务端发送消息
            connection.on("Floor" + f + "CallByHub", function(msg) {
                console.log("收到服务端消息");
                // console.log(msg);
                let serverData = JSON.parse(msg);
                //  console.log(serverData)
                prosServerData(serverData)


                updateLaxianState(plcData)
            });
            //重连之前调用 （只有在掉线的一瞬间，只进入一次）
            connection.onreconnecting(function(error) {
                console.log(connection.state);
                console.log(connection.state === signalR.HubConnectionState.Reconnecting);

            });
            //(默认4次重连)，任何一次只要回调成功，调用
            connection.onreconnected(function(connectionId) {
                console.log(connectionId);
                console.log(connection.state === signalR.HubConnectionState.Connected);
                // 连接成功后 发送消息调用服务器获取数据方法
                connection.send("SendFloor" + f + "ToClient", connection.connectionId).catch(function(err) {
                    return console.error(err.toString());
                });
            });
            //(默认4次重连) 全部都失败后，调用
            // 监听断开连接
            connection.onclose(function() {
                console.log("连接断开")
            })
            //开启连接
            connection.start().then(function() {
                console.log("成功！id = " + connection.connectionId);
                // 连接成功后 发送消息调用服务器获取数据方法
                connection.send("SendFloor1ToClient", connection.connectionId).catch(function(err) {
                    return console.error(err.toString());
                });
            }).catch(function(err) {
                return console.error(err.toString());
            });
             
        }
        window.onbeforeunload = function() {
            graph.destroy()
            connection.off("Floor" + f + "CallByHub");
            connection = null;
            alert("你关闭了浏览器");

        }

        function prosServerData(Data) {
            plcData = {}
            wcsData = {}
            for (let item of Data) {
               // console.log(item);
                console.log("prosServerData:" + item.ProcessModuleName);
                //PLC数据
                if (item.ProcessModuleName.indexOf("PLC") != -1 || item.ProcessModuleName.indexOf("G1State") != -1|| item.ProcessModuleName.indexOf("SC") != -1|| item.ProcessModuleName.indexOf("Ele")) {
                    var equipmentDbObjects = item.equipmentDbObjects;
                    if (equipmentDbObjects.length > 0) {
                        for (let dbObj of equipmentDbObjects) {
                            var equipmentCode = dbObj.EquipmentCode;
                            var bytesObjectBases = dbObj.bytesObjectBases;
                            // var bytesObject = {};
                            if (bytesObjectBases.length > 0) {
                                //  bytesObject = bytesObjectBases[0];
                                for (let objBase of bytesObjectBases) {
                                    // plc数
                                    if (objBase.ObjectType.indexOf("Plc") != -1) {
                                        plcData[equipmentCode] = objBase;
                                    } else if (objBase.ObjectType.indexOf("Wcs") != -1) {
                                        //wcs数据
                                        wcsData[equipmentCode] = objBase;
                                    } else {//其他不可处理的数据
                                        console.log("otherObjectType:" + objBase.ObjectType);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // console.log("plc", plcData);


        }
      
        function updateLaxianState(mydata) {

            // console.log(mydata)

            Object.keys(mydata).forEach((k, index) => {
                var plcItem = mydata[k]
               console.log("收到数据" + k,plcItem)
                for (let it of graph.getNodes()) {


                    if (it.getModel().station == k.trim()) {
                       
                            it.update({
                                data:plcItem
                            })
                    
                        if (it.getModel().class == 'sc') {
                            //堆垛机
                            console.log("sc数据" + k,plcItem,)
                            //堆垛机报警
                            if (plcItem.StackerAlarm) {
                                 if(it.getModel().img!='/images/duiduoji_hong.png'){
                                       it.update({ img: '/images/duiduoji_hong.png' })
                                       graph.refresh(it)
                                 }
                                    
                            } else {//没有报警的其他情况
                                //堆垛机忙或者正在运行中
                                if (plcItem.StackerBusy || plcItem.Stackerrunningsignal) {
                                    if(it.getModel().img!='/images/duiduoji_huang.png'){
                                          it.update({ img: '/images/duiduoji_huang.png' })
                                            graph.refresh(it)
                                    }
                                        

                                } else {
                                    //堆垛机手动
                                    if (plcItem.StackerHandAutomatic) {
                                          if(it.getModel().img!='/images/duiduoji_green.png')
                                             {
                                                  it.update({ img: '/images/duiduoji_green.png' })
                                                    graph.refresh(it)
                                             }

                                    } else {   //堆垛机空闲
                                          if(it.getModel().img!='/images/duiduoji_bai.png'){
                                              it.update({ img: '/images/duiduoji_bai.png' })
                                                graph.refresh(it)
                                          }

                                              

                                    }
                                }
                            }
                        } 
                        else if (it.getModel().class == 'line') {
                            //线体
                                  console.log("line数据" + k,plcItem)
                                //判断线体在线状态
                                if (plcItem.AlrmCode > 0 || plcItem.liftAlrmCode > 0) {

                                    graph.setItemState(it, 'selected', true);



                                } else {

                                    graph.setItemState(it, 'selected', false);
                                }
                                console.log(k + "  " + plcItem.PalletBarcode)
                                //判断托盘
                                if (plcItem.PalletBarcode.replaceAll(" ", "") != "") {
                                    if (it.getModel().stateIcon.show == false)
                                        graph.updateItem(it, {
                                            stateIcon: {

                                                show: true,
                                            }
                                        })
                                } else {
                                    if (it.getModel().stateIcon.show == true)
                                        graph.updateItem(it, {
                                            stateIcon: {

                                                show: false,
                                            }
                                        })
                                }

                            } 
                            
                       else if(it.getModel().class == 'eleLayer'){//提升机
                                  console.log("提升机数据" + k,plcItem)
                                 if (plcItem.AlrmCode > 0 || plcItem.liftAlrmCode > 0) {

                                   if(it.getModel().img!='/images/loucengtisheng.png')
                                     it.update({
                                         img:'/images/loucengtisheng.png'
                                     })


                                } else {

                                   
                               if(it.getModel().img.trim!='/images/loucengtisheng_red.png')
                                     it.update({
                                         img:'/images/loucengtisheng_red.png'
                                     })
                                    
                                }
                            }


                        break;

                    }

                }




            }


            )// console.log(mydata)
        }
        function allSiblings(tag) {
            let parent = tag.parentNode;
            let bro = parent.children;
            let siblings = [];
            for (let i = 0; i <= bro.length - 1; i++) {
                if (bro[i] != tag) {
                    siblings.push(bro[i]);
                }
            }
            return siblings;
        }

        function changeLayer(id) {
            data.currentLayer = id;
            event.target.className = 'active'
            for (const a of allSiblings(event.target)) {
                a.className -= 'active'
            }
            console.log(getQueryVariable('floor') + data.currentLayer)

            $.ajax({
                type: "POST",
                url: "/MonitorEditor/GetMonitorConfigInfoByFloor",
                data: {
                    floor: getQueryVariable('floor') + data.currentLayer.toString()
                },
                dataType: "JSON",
                success: function(result) {
                    console.log(result)
                    if (result.length > 0) {
                        let localData = JSON.parse(result[0].json);



                        // 读取数据
                        if (localData) {
                            graph.changeData(localData, false)
                            console.log("data_" + data.currentFloor + id + "读取")
                            graph.fitView(200);
                        }
                    }



                }
            });



        }

        function getQueryVariable(variable) {
            var query = window.location.search.substring(1);
            var vars = query.split("&");
            for (var i = 0; i < vars.length; i++) {
                var pair = vars[i].split("=");
                if (pair[0] == variable) { return pair[1]; }
            }
            return (false);
        }
    </script>

</body>

</html>